import 'package:get/get.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/msg_entity.dart';
import 'package:oramemo/pages/home/home_logic.dart';
import 'model.dart';

class MsgLogic extends GetxController {
  // 消息列表数据
  final List<MessageModel> list = [];

  int page = 1;

  // 处理消息点击
  void onMessageTap(MessageModel message) {
    // TODO: 处理消息点击事件
    print('Message tapped: ${message.title}');
  }

  // 标记消息为已读
  void markAsRead(MessageModel message) {
    final index = list.indexOf(message);
    if (index != -1) {
      list[index] = MessageModel(
        id: message.id,
        title: message.title,
        content: message.content,
        sender: message.sender,
        avatar: message.avatar,
        time: message.time,
        period: message.period,
        hasNew: false,
      );
      update();
    }
  }

  @override
  void onInit() async {
    await load();
    super.onInit();
  }

  Future<void> load() async {
    await HomeLogic.to.requestDevices();
    update();
    list.clear();
    requestData(page: 1);
  }

  requestData({required int page}) async {
    MsgEntity? res = await DefaultApi().oraUserMessageListGet<MsgEntity>();
    if (res?.rows?.isNotEmpty == true) {
      this.page = page;
      for (MsgRows row in res!.rows!) {
        final DateTime? dateTime =
            row.createTime != null ? DateTime.parse(row.createTime!) : null;
        final String time =
            dateTime?.toString().substring(11, 16) ?? ''; // 获取 HH:mm
        final String date =
            dateTime?.toString().substring(5, 10) ?? ''; // 获取 YYYY-MM-DD
        final MessageModel message = MessageModel(
            id: row.id!,
            title: row.msgTitle ?? '--',
            content: row.msgContent ?? '...',
            sender: '自己',
            avatar: '',
            time: time,
            hasNew: row.realStatus == 1,
            period: date);
        list.add(message);
      }
    }
    update();
  }
}
